package cn.baage.campus.config.security.auth;

import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Description: 微信认证 provider
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@Data
public class WxProvider implements AuthenticationProvider {

    // 设置 WxUserDetailsService
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxAuthenticationToken wxAuthenticationToken = (WxAuthenticationToken) authentication;
        String wxId = wxAuthenticationToken.getPrincipal().toString();
        // 使用 WxUserDetailsService 获取用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(wxId);
        if (userDetails == null) {
            return null;
        }
        // 返回认证结果信息，供调用者处理认证后的操作 AuthServiceImpl#loginByWx
        WxAuthenticationToken authenticationResult = new WxAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(userDetails);
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 处理类型为 WxAuthenticationToken 或其子类的 AuthenticationToken
        return (WxAuthenticationToken.class.isAssignableFrom(authentication));
    }



}
